<template >
	<div style='background:#FFC8B4' class='cle'>
		<van-button class='enterGoods'v-if="isLogin" type="danger" @click="entryGoodsToDb">录入商品</van-button>
		<!-- 横向分类栏 -->
		<div class="wrapDiv cle">
	        <van-tabs  @click ='headColumnFn' v-model="tabActive" animated>
	          	<van-tab v-for="(item,inx) in goodsCategoryData" :key=inx :title=item.n>
					  <!-- <h1>{{item.d}}</h1> -->
					    <!-- //轮播图 -->
						<van-swipe :autoplay="2800" class='sliderDiv'>
							<van-swipe-item v-for="(item, index) in goodsSliderData" :key="index">
									<img v-lazy="item.img" />
							</van-swipe-item>
						</van-swipe>
					  
				</van-tab>
	        </van-tabs>
		</div>  

		<!-- 商品录入框 -->
		<div v-if="isEntryGoods" class="goodsEntry cle">
				<div v-for="item in emptyGoodsDomArr">
					<entryGoods 
						@pushGoodsInfo="pushGoodsInfoFn"
						@isVoidFalse="isVoidFalseFn"
						/>
				</div>
			<van-button type="danger" @click="addGoodsInputBtn">+</van-button>
			<van-button type="danger" @click="submitBtn">提交</van-button>
			<van-button type="danger" @click="cancelBtn">取消</van-button>
		</div>
		<div class='entryGoodsDivBg' v-if='isEntryGoodsDivBg'></div>
		
		
		<!-- 竖向分类栏 -->
		<div class='sideBarFn' >
			<van-sidebar v-model="activeSideBarKey" @change="onSideBarChange"class='verItem'>
				<van-sidebar-item v-for="(item,inx) in goodsCategoryData" 
					:key=inx
				 	:title=item.n  />
			</van-sidebar>
		</div>

		<!-- 显示竖向栏目的数据 -->
		<div>
			<div class='columnData'>
				<ul v-for='item in goodsListData' @click= 'goToGoodsProduct(item)'>
					<li><img :src="item.img" /></li>
					<li>{{item.name}}</li>
					<li>￥{{item.price}}</li>
					<!-- <li>{{item.describe}}</li> -->
				</ul>
			</div>

			<!-- 分页 -->
			<div class='pageChange'>
				<van-pagination 
					v-model="currentPage" 
					:total-items= 'totalItems'
					:items-per-page = 'itemPerPage'
					mode="simple" 
					@change='pageChangeFn'
					/>
			</div>
		</div>


		
		<footerBar></footerBar>
	</div>
</template>

<script>
import axios from 'axios'
import API_LIST from '@/APIList.config'
import footerBar from './footerBar'
import entryGoods from './entryGoods'

export default{
	name:'goodsType',
	data(){
		return {
			//轮播图的数据
			goodsSliderData:'',
			//分页当前页
			currentPage:1,
			//总商品记录数
			totalItems:0,
			//分页每一页的记录数
			itemPerPage:3,
			//竖向分类栏
			activeSideBarKey:0,

			tabActive:0,
			//退出登录显示与否//应该是录入商品显示与否,true表示显示
            isLogin : false,

			//录入商品显示与否
			isEntryGoods:false,

			// 四框是否全填完,true表示填完了
			isGoodsInfoWrite:false,
			//传入商品的名字是否重复 true 表示没重名
			isNameRepeat:true,
			// 空白的录入框
			emptyGoodsDomArr:[{}],
			//录入框背景
			isEntryGoodsDivBg:false,
			// 每次接收录入商品信息
			entryGoodsObj:[],

			//获得商品大类
			goodsCategoryData:'',

			//属性栏目的商品
			goodsListData:[]
		}
	},
	components:{footerBar,entryGoods},
	created(){

		//获得商品列表-大类
		this.getGoodsCategoryFn();

		//竖向分类栏点击事件
		this.getCatagoryGoodsListFn('goodsList_a');
		//分页
		this.pageChangeFn();

		//如果没有数据下面的都不执行
		if(!localStorage.userName){
			return 
		}

		//要把localStorage转成对象，才能作为对象使用
		let _str= JSON.parse(localStorage.userName)
		if( localStorage.userName ){
				this.$notify( _str.username + '您已经登录，欢迎回来！' );
		}   
	
		if(localStorage.userName && _str.username == '约翰'){
			this.isLogin = true;
		};
		
	},
	watch:{
		activeSideBarKey(_inx){
			let _c= this.goodsCategoryData[_inx].d;
			this.getCatagoryGoodsListFn(_c);
			//放在watch，而不是onSideBarChange 中
			this.currentPage=1;
			this.pageChangeFn();

		}
	},
	methods:{

			//转到商品详情页
			goToGoodsProduct(_item){
				//console.log(_item)
				this.$router.push({
					name:'goodsProduct',
					query:{
							_goodsObjId:_item._id,
							_collectionsName:_item.category
					}
                  })
			},
			//分页点击触发
			pageChangeFn(){
				// console.log(this.currentPage);
				//分类页的算法
				//console.log(this.goodsCategoryData)
				let _c='';
				if(!this.goodsCategoryData){
					_c= 'goodsList_a'
				}else{
					_c= this.goodsCategoryData[this.activeSideBarKey].d;
				}

				//console.log(_c,(this.currentPage-1))
			axios.get(API_LIST.getPageChange,{
					params:{
						startNum: (this.currentPage-1)*this.itemPerPage,
						c:_c
					}
				})
				.then((_d)=>{
					//console.log(_d.data);
					this.goodsListData =_d.data
				}) 
			},
			//横向分类栏
			headColumnFn(_inx){
				//console.log(this.tabActive);
				//上面的 传递的 _inx 其实就是this.tabActive
				//横向栏目点击事件改变 纵向栏目索引
				this.activeSideBarKey= _inx
			},
			//竖向分类栏点击事件
			onSideBarChange(_key){
				//console.log(_key)
				//console.log(this.goodsCategoryData[_key].n)
				//console.log(this.goodsCategoryData[_key].d)

				let _c= this.goodsCategoryData[_key].d;
				//因为改成分页获取数据的形式，所以下面这个方法注释掉
				// this.getCatagoryGoodsListFn(_c);


				//纵向栏目点击事件改变 横向栏目索引
				this.tabActive= _key;

			},
			//查询栏目所属商品列表
			getCatagoryGoodsListFn(_c){
				axios.get(API_LIST.getCataGoryGoodsList,{
					params: {categoryId: _c}
					})
					.then((_d)=>{
					//console.log(_d.data);
					//这里是= 而不是+=
					//this.goodsListData =_d.data;

					//分类下的所有商品的总数，用在分页上
					this.goodsSliderData= _d.data;
					this.totalItems= _d.data.length;
				})
			},


			// 获得商品列表-大类
			getGoodsCategoryFn(){
				axios.get( API_LIST.getGoodsCategory )
					.then( _d =>{
						//console.log( _d.data )
						this.goodsCategoryData = _d.data;
					})
			},
		     // 录入商品
            entryGoodsToDb(){
				  this.isEntryGoods = true;
				  this.isEntryGoodsDivBg=true;
            },

            // 四个框没写完时，触发
            isVoidFalseFn(){
                  this.isGoodsInfoWrite = false;
            },
            
            // 添加商品信息到，总的商品信息的数组的对象
            pushGoodsInfoFn( _goodsInfoObj ){
                  // 四个框全写完了
                  this.isGoodsInfoWrite = true;

                  // 判断 商品名称是否重复，true表示没有重复；false表示重复了
                  let _is = true;

                  for(let i=0; i<this.entryGoodsObj.length; i++){
                        if( this.entryGoodsObj[i].n === _goodsInfoObj.n ){
                              _is = false;
                              break;
                        }
                  }

                  if( _is ){
                        this.entryGoodsObj.push( _goodsInfoObj );
                        this.isNameRepeat = true;
                        //console.log(this.entryGoodsObj)
                  } else {
                        this.isNameRepeat = false;
                        this.$dialog.alert({
                              message : '商品重名了'
                        });
                  }

            },

            // 四个框全填完，并且不重名，才能增加新的空白框
            addGoodsInputBtn(){
                  let _is = ''
                  if( this.isGoodsInfoWrite && this.isNameRepeat ){
                        this.emptyGoodsDomArr.push( {} );
                        this.isGoodsInfoWrite= false;
                        this.isNameRepeat = false;
                  } else {
                        // 这里的逻辑暂时就先不搞那么复杂了
                        this.$dialog.alert({
                              message : '有框还没写完，或者，商品重名'
                        });
                  }
            },

            // 提交新增商品
            submitBtn(){
                  //console.log( this.entryGoodsObj );

                  axios.post( API_LIST.insertGoods,this.entryGoodsObj )
                        .then( _d=>{
                              //console.log(_d.data);

                              this.$dialog.alert({
                                    message : _d.data.regInfo
                              }).then(()=>{
                                    // 商品录入窗口关闭；
                                    this.isEntryGoods = false;
                                    // 空白输入框的数量重置
									this.emptyGoodsDomArr = [{}];
									//每次接收录入商品信息
									this.entryGoodsObj=[]

                                    // 获得商品列表-大类，更新页面
									this.getGoodsCategoryFn();
									//录入框背景关掉
									this.isEntryGoodsDivBg=false;
                              });
                        }) 
			},

			//取消提交商品输入框
			cancelBtn(){
				this.isEntryGoods = false;
				this.isEntryGoodsDivBg=false;
			}
	}
}
</script>

<style scoped>
	
	h1, h2 {
		font-weight: normal;
	}
	ul {
		list-style-type: none;
		padding: 0;
	}
	li {
		display: inline-block;
		margin: 0 10px;
	}
	a {
		color: #42b983;
	}
	.cle:after{
			content: '.';
			overflow: hidden;
			visibility: hidden;
			height: 0;
			display: block;
			clear: both;
		}
	.wrapDiv{
		width: 85%;overflow: hidden;border: 1px solid #eee;
		border-radius: 10px;background: #fff;
		margin:0 auto;
	}
	.wrapDiv p.tip{
		font-size: 22px;text-align: center;padding: 0;margin:5px 0;color: #666;
	}
	.leftDiv{
		float: left;width: 60%;margin:10px;
		border-radius: 10px;border:1px solid #999;
		padding:10px;line-height: 30px;text-align: center;
		font-size: 22px;
	}
	.rightDiv{
		float: right;width: 20%;margin:10px;
		border-radius: 10px;border:1px solid #999;
		padding:10px;line-height: 30px;text-align: center;
		font-size: 22px;
	}
	.sliderDiv{
		width: 80%;margin:10px auto;
	}
	.sliderDiv img{width:100%;height:188px;}

	.goodsEntry{
		width: 80%; position: absolute;top: 10%;left: 50%;margin-left: -42%;
		z-index: 112;padding:10px;background:#fff;
		border-radius: 10px;
		line-height: 30px;text-align: center;
		font-size: 16px;
	}

	.goodsCategory{clear: both;margin: 10px 0;}
	.goodsCategory li{float: left; }
	.goodsCategory li img{
			width: 50px;height: 50px;border-radius: 10px;
			border:1px solid #ddd;
		}
	.entryGoodsDivBg{
		width: 100%;height: 100%;background: #000;opacity: 0.4;
		z-index: 111;position: absolute;top: 0;left: 0;
	}
	.imgSize{width: 100%;height: 100%;}
	.sideBarFn{
			position: absolute;top: 355px;left: 0;z-index: 10;
		}
	.verItem{
		width:60px;
	}
	.columnData{
		position:relative;
		left:-24px;
		clear: both;width: 75%;height:454px;
		background: #FFC8B4;
		border-radius: 5px;
		margin:0 0 0 90px;
	}
	.columnData ul{
	display: block;clear: both;overflow: hidden;margin:10px 0;
	background: #fff;
	border-radius: 10px;
	}
	.columnData ul li{
		float: left;margin:5px;font-size:25px; ;
	}
	
	.columnData ul li img{
		width:110px;height: 114px;
	}
	.pageChange{position: absolute;right:0;bottom:50px;
		width: 85%;clear: both; list-style:none;
	}
	.sliderDiv{
        width:85%;margin:10px auto;
      }
    .sliderDiv img{width:60%;height:140px;}
	.enterGoods{
		border-redius: 100%;
		 width:150px;height:32px;margin:8px auto; line-height:32px;
	}
</style>